﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using Imager.Properties;

namespace ConusicUI
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;

    /// <summary>
    /// Description of ErrorReport.
    /// </summary>
    public partial class ErrorReport : Form
    {
        public static void Show(Exception occuredException, IWin32Window owner = null)
        {
            var errorReportWindow = new ErrorReport(occuredException);
            errorReportWindow.ShowDialog(owner);
            if(owner != null)
            {
                FromHandle(owner.Handle).Select();
            }
            errorReportWindow.Dispose();
        }

        public static void ShowPopup(string message, Control owner)
        {
            var tt = new ToolTip();
            tt.IsBalloon = false;
            tt.ToolTipIcon = ToolTipIcon.Warning;
            tt.ShowAlways = true;
            tt.BackColor = Color.FromArgb(0xFF, 0xFF, 0x90);
            tt.ToolTipTitle = "Conusic";
            tt.Show(message, owner);
            var ts = new ThreadStart(delegate { RemoveOldErrorHint(tt, owner); });
            var thread = new Thread(ts);
            thread.Start();
        }

        private static void RemoveOldErrorHint(ToolTip tt, Control owner)
        {
            Thread.Sleep(5000);
            if (!owner.Created) return;
            
            owner.Invoke(new MethodInvoker(() =>
                                               {
                                                   tt.RemoveAll();
                                                   tt.Dispose();
                                               }));
        }

        private ErrorReport(Exception occuredException)
        {
            InitializeComponent();

            //this.savedException = occuredException;
            if (occuredException != null)
            {
                var variables = new StringBuilder("user variables: \r\n");
                foreach (KeyValuePair<string, string> item in occuredException.Data)
                {
                    variables.AppendFormat("{0} = {1}\r\n", item.Key, item.Value);
                }

                string exceptionString = String.Format("{1}{0}{0}{2}{0}{0}{3}{0}{0}{4}",
                    Environment.NewLine,
                    occuredException.Message,
                    occuredException.StackTrace,
                    occuredException.Source,
                    variables.ToString());


                var binaryFormatter = new BinaryFormatter();

                Stream serializationStream = new MemoryStream(1024);
                binaryFormatter.Serialize(serializationStream, occuredException);
                serializationStream.Position = 0;
                byte[] arr = new byte[serializationStream.Length];
                serializationStream.Position = 0;
                serializationStream.Read(arr, 0, arr.Length);
                textBoxErrorSharp.Text = Convert.ToBase64String(arr);
                serializationStream.Dispose();

                this.textBoxDetails.Text = String.Format(
                    Resources.ErrorReport_CommentFormat,
                    Application.ProductVersion,
                    Environment.OSVersion,
                    exceptionString,
                    Environment.Version);

                // Comment, because i receive a lot of error reports what i not to know to do :-(
                // (without any description)
                //this.textBoxContact.Text = Conusic.Config.Instance.GetStringParam("email");
            }
            else
            {
                this.textBoxErrorSharp.Text = @"Передан нулевой агрумент в обработчик ошибок. ";
            }
        }

        private void ButtonSendClick(object sender, EventArgs e)
        {
            if (textBoxContact.Text.Equals(String.Empty))
            {
                errorProvider1.SetError(textBoxContact, "Укажите ваш адрес");

            }
            else
            {
                string dataString = String.Format(
                    Resources.ErrorReport_SendStringFormat,
                    textBoxContact.Text,
                    textBoxErrorSharp.Text,
                    textBoxDetails.Text);
                dataString = dataString.Replace(Environment.NewLine, "<br />");

                try
                {
                    var page = Conusic.SimpleHttp.RequestPage("http://3po.ru/feedback.php",
                               String.Format(
                                   "email={0}&desc={1}",
                                   System.Web.HttpUtility.UrlEncode(textBoxContact.Text),
                                   System.Web.HttpUtility.UrlEncode(dataString)
                                   ));

                    if (page.Equals("ok"))
                    {
                        MessageBox.Show(this, @"Спасибо. Сообщение отправлено.", @"Успех", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                        this.Close();
                    }
                    else
                    {
                        throw new ApplicationException();
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(Resources.ErrorReport_errorSendString + dataString, "Ошибка", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }

            }
        }

        private void ButtonCancelClick(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}